import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:queue_flutter/api.dart';
import 'package:queue_flutter/queue_obj.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

import 'const.dart';

class CallerPage extends StatefulWidget {
  const CallerPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _CallerPageState();
  }
}

class _CallerPageState extends State<CallerPage> {
  final textFieldController = TextEditingController();
  final CONST = Const();
  final api = Api();
  var _bulletin = "";
  var _name = "";
  var _userId = "";
  var _code = "";
  late Future<QueueList> futureQueueList = Future.value(QueueList());

  Future<void> _getUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _userId = prefs.getString("userId") ?? "";
      _name = prefs.getString("name") ?? "";
    });
  }

  Future<void> _getOrCreateQueue() async {
    await _getUserInfo();

    QueueList? queueList = await api.getQueue(_userId);

    if (queueList == null) {
      QueueList createdQueueList = await api.createQueue(_name, _userId);
      setState(() {
        _code = createdQueueList.code ?? "";
        futureQueueList = Future.value(createdQueueList);
      });
    } else {
      setState(() {
        _bulletin = queueList.bulletin ?? "";
        _code = queueList.code ?? "";
        textFieldController.text = _bulletin;
        futureQueueList = Future.value(queueList);
      });
    }
  }

  Future<void> _updateBulletin() async {
    await api.updateCaller(_code, _userId, textFieldController.text);
  }

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    _getOrCreateQueue();
  }

  Future<void> confirmDeleteQueue() async {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Are you sure to delete this queue?'),
            content: Text('There are still 18 person in queue.'),
            actions: [
              TextButton(
                  onPressed: () =>
                      {Navigator.of(context, rootNavigator: true).pop()},
                  child: const Text('Cancel')),
              TextButton(
                  onPressed: () {
                    deleteQueue();
                  },
                  child: const Text('Delete'))
            ],
          );
        });
  }

  Future<void> deleteQueue() async {
    await api.deleteQueue(_userId).then((isSuccess) => {
          if (isSuccess)
            {
              Navigator.of(context, rootNavigator: true).pop(),
              Navigator.popUntil(context, ModalRoute.withName('/'))
            }
        });
  }

  void callNext() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Call next one!'),
            content: Text('The next one will be Tianyang.'),
            actions: [
              TextButton(
                  onPressed: () =>
                      {Navigator.of(context, rootNavigator: true).pop()},
                  child: const Text('Cancel')),
              TextButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                  },
                  child: const Text('Call Next'))
            ],
          );
        });
  }

  void setBulletin() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Set a bulletin'),
            content: TextField(
              controller: textFieldController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: 'Bulletin',
              ),
              maxLines: 4,
            ),
            actions: [
              TextButton(
                  onPressed: () =>
                      {Navigator.of(context, rootNavigator: true).pop()},
                  child: const Text('Cancel')),
              TextButton(
                  onPressed: () {
                    _updateBulletin();
                    Navigator.of(context, rootNavigator: true).pop();
                    setState(() {
                      _bulletin = textFieldController.text;
                    });
                  },
                  child: const Text('Save'))
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text('Caller'),
        actions: [
          IconButton(
              onPressed: () => {setBulletin()},
              icon: const Icon(
                Icons.comment,
                semanticLabel: 'settings',
              ))
        ],
      ),
      body: Center(
          child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: const Text(
              'Your queue list number is:',
            ),
          ),
          FutureBuilder<QueueList>(
            future: futureQueueList as Future<QueueList>?,
            builder: (context, snapshot) {
              if (snapshot.hasData && snapshot.data!.userId != null) {
                return Text(
                  snapshot.data!.code ?? "",
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 24,
                      letterSpacing: 16),
                );
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }
              return const CircularProgressIndicator();
            },
          ),
          if (_bulletin != "")
            Padding(
              padding: const EdgeInsets.only(left: 8.0, right: 8.0),
              child: SizedBox(
                width: double.infinity,
                child: Card(
                    child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      Text(
                          'You left a bulletin that everyone in queue can see:'),
                      Text(_bulletin,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ))
                    ],
                  ),
                )),
              ),
            ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: ListView(
                children: const <Widget>[
                  Card(
                      child: ListTile(
                          title: Text('Haonan'),
                          subtitle: Text('Talk is cheap, show me your code.'))),
                  Card(
                      child: ListTile(
                    title: Text('Yunhao'),
                    subtitle: Text('Photographing is my life.'),
                  )),
                  Card(
                      child: ListTile(
                          title: Text('Tianyang'),
                          subtitle: Text('I like Coca cola!'))),
                  Card(
                      child: ListTile(
                          title: Text('Tianjia'),
                          subtitle: Text('Practice makes perfect.'))),
                  Card(
                      child: ListTile(
                          title: Text('Haonan'),
                          subtitle: Text('Talk is cheap, show me your code.'))),
                  Card(
                      child: ListTile(
                          title: Text('Yunhao'),
                          subtitle: Text('Photographing is my life.'),
                          trailing: Icon(Icons.check_circle_outline))),
                  Card(
                      child: ListTile(
                          title: Text('Tianyang'),
                          subtitle: Text('I like Coca cola!'))),
                  Card(
                      child: ListTile(
                          title: Text('Tianjia'),
                          subtitle: Text('Practice makes perfect.'))),
                  Card(
                      child: ListTile(
                          title: Text('Haonan'),
                          subtitle: Text('Talk is cheap, show me your code.'))),
                  Card(
                      child: ListTile(
                    title: Text('Yunhao'),
                    subtitle: Text('Photographing is my life.'),
                  )),
                  Card(
                      child: ListTile(
                          title: Text('Tianyang'),
                          subtitle: Text('I like Coca cola!'))),
                  Card(
                      child: ListTile(
                          title: Text('Tianjia'),
                          subtitle: Text('Practice makes perfect.'))),
                  Card(
                      child: ListTile(
                          title: Text('Haonan'),
                          subtitle: Text('Talk is cheap, show me your code.'))),
                  Card(
                      child: ListTile(
                    title: Text('Yunhao'),
                    subtitle: Text('Photographing is my life.'),
                  )),
                  Card(
                      child: ListTile(
                          title: Text('Tianyang'),
                          subtitle: Text('I like Coca cola!'))),
                  Card(
                      child: ListTile(
                          title: Text('Tianjia'),
                          subtitle: Text('Practice makes perfect.'))),
                ],
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  height: 48,
                  child: FilledButton(
                    onPressed: () => {confirmDeleteQueue()},
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Theme.of(context).colorScheme.primary),
                    child: Icon(
                      Icons.delete,
                      color: Theme.of(context).colorScheme.onPrimary,
                    ),
                  ),
                ),
                Padding(padding: EdgeInsets.all(8)),
                Expanded(
                  child: SizedBox(
                    height: 48,
                    child: FilledButton.tonalIcon(
                      onPressed: () => {callNext()},
                      label: Text('Next One'),
                      icon: Icon(Icons.next_plan),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      )),
    );
  }
}
